#include "lyricparser.h"
#include <QFile>
#include <QTextStream>
#include <QRegularExpression>

LyricParser::LyricParser(QObject *parent) : QObject(parent)
{
}

bool LyricParser::loadLyricFile(const QString &filePath)
{
    clear();
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return false;
    }

    QTextStream in(&file);
    in.setCodec("UTF-8");  // 设置编码为UTF-8

    // 匹配时间标签的正则表达式 [mm:ss.xx]
    QRegularExpression timeRegex("\\[(\\d{2}):(\\d{2})\\.(\\d{2})\\]");

    while (!in.atEnd()) {
        QString line = in.readLine();
        
        // 查找所有时间标签
        int pos = 0;
        QRegularExpressionMatch match;
        while ((match = timeRegex.match(line, pos)).hasMatch()) {
            pos = match.capturedEnd();
            
            // 解析时间
            int minutes = match.captured(1).toInt();
            int seconds = match.captured(2).toInt();
            int milliseconds = match.captured(3).toInt() * 10;
            qint64 timestamp = (minutes * 60 + seconds) * 1000 + milliseconds;
            
            // 提取歌词文本（移除所有时间标签）
            QString lyricText = line.mid(pos);
            lyricText.remove(QRegularExpression("\\[\\d{2}:\\d{2}\\.\\d{2}\\]"));
            
            if (!lyricText.trimmed().isEmpty()) {
                lyrics.insert(timestamp, lyricText.trimmed());
            }
        }
    }

    file.close();
    return true;
}

QString LyricParser::getLyricByTime(qint64 time)
{
    auto it = lyrics.upperBound(time);
    if (it == lyrics.begin()) {
        return lyrics.isEmpty() ? QString() : lyrics.first();
    }
    --it;
    return it.value();
}

void LyricParser::clear()
{
    lyrics.clear();
} 